#!/usr/bin/env Rscript
{
  # download LinkOrgs package remotely: 
  # devtools::install_github('cjerzak/LinkOrgs-software/LinkOrgs')
  
  # download other required packages: 
  # install.packages("fastmatch")
  
  # local install for development team: 
  # (download package into temporary directory for development team debugging purposes)
  # Sys.setenv("R_LIBS_USER"="/tmp/libDemo/lib"); devtools::install_github('cjerzak/LinkOrgs-software/LinkOrgs')
  
  # build LinkOrgs backend (do this only once after installing the latest version of LinkOrgs)
  # LinkOrgs::BuildBackend(conda_env = "LinkOrgsEnv", tryMetal = T) 
  # try to see if the jax-metal backend can be installed on Mac; if this fails, set tryMetal = F
  
  # set working directory to replication files repo 
  rm(list=ls())
  setwd('~/Dropbox/Directory')

  # set JustEvaluateResults to T to re-create figures (~1 minute runtime on local hardware)
  # set JustEvaluateResults to F to re-run full analysis (~24 hours runtime on local hardware)
  JustEvaluateResults <- F
  JustRunTestAnalysis <- F
  
  # set environment
  set.seed( 1 )
  nCoresUse <- 10L # set to number of cores on your machine minus 2 
  reduceData <- F
  CondaEnvToUse <- "LinkOrgsEnv"
  ml_version <- "v1" 
  deezyLoc <- './Analysis/DeezyCode/DeezyMatch'
  if(Sys.info()['nodename'] == "pop-os"){ nCoresUse <- 24L; CondaEnvToUse <- "jax_gpu" }

  # helper functions 
  library(LinkOrgs); library(fastmatch)
  FirstLetterUpper <- function(x) {substr(x, 1, 1) <- toupper(substr(x, 1, 1)); return( x ) }
  f2n <- function(ze){as.numeric(as.character(ze))}
  ReSaveDataAssets <- F

  # example directory:
  #exampleNum = 2 # -> libgober analysis (687 by 6886)
  #exampleNum = 4 # -> market cap analysis (8592 by 1000)
  #exampleNum = 5 # -> non-latin linkage example (766 by 766)
  #exampleNum = 6 # -> person name match (incomplete)
  #exampleNum = 7 # -> ycombinator name matches

  # set grid parameters
  qgramMaster = 2;
  
  if(JustRunTestAnalysis){
    # run reduced analysis for testing purposes 
    my_grid <- expand.grid(
      "exampleNum_i" = c(theExamples <- 5),
      "algorithm_i" = c("bipartite","markov","ml","fuzzy"),
      "distanceMeasure_i" =  c(FuzzyDistanceMeasureMaster <- 'jaccard', "ml") )
  }
  if(!JustRunTestAnalysis){
    #  run full analysis
    my_grid <- expand.grid(
      "exampleNum_i" = (theExamples <- c(5, 2, 4, 7)),
      "algorithm_i" = c("bipartite","markov","ml","fuzzy"),
      "distanceMeasure_i" =  c(FuzzyDistanceMeasureMaster <- 'jaccard', "ml") )
  }
  my_grid <- rbind(my_grid, expand.grid(
                     "exampleNum_i" =  theExamples,
                     "algorithm_i" =  c( "transfer"),
                     "distanceMeasure_i" =  c( "transfer") ))
  my_grid <- rbind(my_grid, expand.grid(
                      "exampleNum_i" =  theExamples,
                      "algorithm_i" =  c( "DeezyMatch"),
                      "distanceMeasure_i" =  c( "DeezyMatch") ))
  my_grid <- rbind(my_grid, expand.grid(
                    "exampleNum_i" =  theExamples,
                    "algorithm_i" =  c( "lookup"),
                    "distanceMeasure_i" =  c( "jaccard") ))

  # general restrictions
  my_grid <- my_grid[!(my_grid$algorithm_i == "ml" &  my_grid$distanceMeasure_i != "ml"),]
  my_grid <- my_grid[!(my_grid$algorithm_i == "fuzzy" &  my_grid$distanceMeasure_i != FuzzyDistanceMeasureMaster),]
  my_grid <- my_grid[my_grid$algorithm_i != "transfer",]

  # specific subsets for additional testing
  #my_grid <- my_grid[7:8,]
  
  # reset rownames
  row.names(my_grid) <- 1:nrow(my_grid)
  LinkOrgs::print2(sprintf("Grid dims: [%s, %s]", dim( my_grid)[1], dim( my_grid)[2]))

  # setup iterator
  COMMAND_ARG_INPUT <- try(as.integer((args <- commandArgs(TRUE))[1]),T)
  if(!is.na(COMMAND_ARG_INPUT)){ OUTER_ITERATION_SEQUENCE <- COMMAND_ARG_INPUT }
  if(is.na(COMMAND_ARG_INPUT)){ OUTER_ITERATION_SEQUENCE <- 1:nrow(my_grid)  }

  if(!JustEvaluateResults){
    source("./Analysis/LinkOrgs_EmpiricalExamples_Run.R" )
  }

  if(JustEvaluateResults){
    source("./Analysis/LinkOrgs_EmpiricalExamples_Evaluate.R" )
  }
}

